﻿/// <reference path="../jquery-1.7.2-vsdoc.js" />

$(document).ready(function () {
    $("form:first").submit(saveQuestionnaire);
});

var alertValidation = false;

function saveQuestionnaire() {
    var result = new Object();

    var i = 0;
    var j = 0;

    result.ActivityID = $('#ActivityID').val();
    result.StudyID = $('#StudyID').val();

    result.RemainingCrtActivity = $('#RemainingCrtActivity').val();
    result.RemainingCrtGroup = $('#RemainingCrtGroup').val();
    result.RemainingCrtSession = $('#RemainingCrtSession').val();

    result.ProtocolActivityId = $('#ProtocolActivityId').val();
    result.ProtocolGroupId = $('#ProtocolGroupId').val();
    result.ProtocolSessionId = $('#ProtocolSessionId').val();

    result.IsForApproval = $('#IsForApproval').val();


    result.Questions = new Array();
    $('#qList').children('li').each(function () {
        result.Questions[i] = new Object();
        var questionAttr = $(this).attr('id').split('_');
        result.Questions[i].ID = questionAttr[1];
        result.Questions[i].HasFreeAnswer = questionAttr[2] == 1;
        result.Questions[i].HasMultipleChoice = questionAttr[3] == 1;
        if (result.Questions[i].HasFreeAnswer) {
            result.Questions[i].FreeAnswer = $(this).find('#qAnswer').val();
            if (result.Questions[i].FreeAnswer == "" && !alertValidation) {
                alert('Make sure that you answer all question');
                alertValidation = true;
            }
        } else if (!result.Questions[i].HasMultipleChoice) {
            var singleAnswer = $(this).find('input:radio[id^="aList"]:checked').val();
            if (singleAnswer) {
                result.Questions[i].SingleAnswerID = singleAnswer.replace('answer', '');
            } else {
                if (!alertValidation) {
                    alert('Make sure that you answer all question');
                    alertValidation = true;
                }
            }
        } else {
            result.Questions[i].Answers = new Array();
            j = 0;
            $(this).find('[id^="aList"]').find('input:checkbox:checked').each(function () {
                result.Questions[i].Answers[j] = $(this).attr('id').replace('answer', '');
                j++;
            });
            if (j == 0 && !alertValidation) {
                alert('Make sure that you answer all question');
                alertValidation = true;
            }
        }
        i++;
    });

    if (alertValidation) {
        alertValidation = false;
        return false;
    } else {
        $('#jsonResult').val(JSON.stringify(result));
        return true;
    }
}
